<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\BaseController;
use App\Models\Article;
use App\Models\Comment;
use App\Models\Star;
use Illuminate\Http\Request;

class CommentController extends BaseController
{
    public $model = Comment::class;

    public function index(Request $request) {
        $search = ['start_at' => '', 'end_at' => '', 'user_id' => '', 'user.nickname' => '', 'message' => ''];
        $input = $request->input();

        $user_id = $this->getUserId();
        $list = Comment::apply($search, $input)->withCertain('user', ['nickname', 'avatar_url'])
             ->withCount(['is_star' => function ($qr) use ($user_id) {
                 $qr->where('user_id', $user_id)->where('type', Star::TYPE_COMMENT);
             }])
            ->with('entity')
            ->withCertain('entity_user', ['nickname', 'avatar_url'])
            ->with('reply')
            ->with('parent')
            ->orderBy("id", "desc");

        $list = $list->paginate(per_page());
        return $this->paginate($list);
    }



    /**
     * 删除
     * @param Request $request
     * @return mixed
     * @throws \Illuminate\Validation\ValidationException
     * @throws \Throwable
     */
    public function destroy(Request $request)
    {
        $this->validate($request, [
            'ids' => 'required',
        ]);
        $ids = \request('ids');
        \DB::transaction(function () use($ids) {
            $arr_id = explode(",", $ids);
            foreach ($arr_id as $id) {
                $comment = Comment::find($id);
                $entity_id = $comment->entity_id;
                if (!$comment)
                    return $this->failed("评论不存在");

                $parent_id = $comment->parent_id;
                if ($parent_id == 0) {
                    Comment::where('parent_id', $comment->id)->delete();
                }
                $comment->delete();
                $comment_num = Comment::where('entity_id', $entity_id)->count();
                Article::where('id', $entity_id)->update(['comment_num' => $comment_num, 'latest_comment_at' => time()]);
            }
        });

        return $this->success([]);
    }


}

